package com.zk.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectById;
import com.baomidou.mybatisplus.core.injector.methods.SelectOne;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zk.yygh.enums.AuthStatusEnum;
import com.zk.yygh.hosp.exception.HospitalException;
import com.zk.yygh.hosp.helper.JwtHelper;
import com.zk.yygh.hosp.result.Result;
import com.zk.yygh.hosp.result.ResultCodeEnum;
import com.zk.yygh.model.user.Patient;
import com.zk.yygh.model.user.UserInfo;
import com.zk.yygh.user.mapper.UserInfoMapper;
import com.zk.yygh.user.service.PatientService;
import com.zk.yygh.user.service.UserInfoService;
import com.zk.yygh.vo.user.LoginVo;
import com.zk.yygh.vo.user.UserAuthVo;
import com.zk.yygh.vo.user.UserInfoQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 张凯
 * @date: 2022/6/12 - 14:33
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //就诊人
    @Autowired
    private PatientService patientService;

    //手机登录
    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        //1.获取登录信息(手机号+验证码)
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //2.判断登录信息是否为空
        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(code)){
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        }
        //3.校验验证码
        String phoneCode = redisTemplate.opsForValue().get(loginVo.getPhone());
        if (!phoneCode.equals(code)){
            throw new HospitalException(ResultCodeEnum.CODE_ERROR);
        }
        //4.给微信登录用户绑定手机号
        UserInfo user=null;
        System.out.println("查询的openId: "+loginVo.getOpenid());
        if(!StringUtils.isEmpty(loginVo.getOpenid())){  //微信用户
            user = this.selectUserInfoByOpenId(loginVo.getOpenid());
            System.out.println("根据openId查询的user:"+user);
            if (user!=null){
                if (user.getPhone()==null){
                    //给微信用户绑定手机号及完善信息
                    user.setPhone(loginVo.getPhone());
                    user.setStatus(1);
                    user.setName("");
                    System.out.println("更新的user:"+user);
                    this.updateById(user);
                }
            }else {
                throw new HospitalException(ResultCodeEnum.DATA_ERROR);
            }
        }
        //5.查询数据库判断是登录还是注册:微信用户为空则走手机用户登录
        if (user==null){    //手机用户
            user = baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("phone", phone));
            if (user==null){    //用户注册
                //未查询到用户，则注册该用户
                user=new UserInfo();
                user.setPhone(phone);
                user.setStatus(1);
                user.setName("");
                this.save(user);
            }
        }
        //6.判断用户是否被封号
        if (user.getStatus()==0){
            throw new HospitalException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        //7.封装和返回结果信息(name+token)
        Map<String,Object> res=new HashMap<>();
        String name="";
        if (!StringUtils.isEmpty(user.getName())){
            name=user.getName();
        }else if (!StringUtils.isEmpty(user.getNickName())){
            name=user.getNickName();
        }else {
            name=user.getPhone();
        }
        res.put("name",name);
        res.put("token", JwtHelper.createToken(user.getId(),user.getName()));
        return res;
    }

    //根据openId查询UserInfo
    @Override
    public UserInfo selectUserInfoByOpenId(String openId) {
        return baseMapper.selectOne(new QueryWrapper<UserInfo>().eq("openid",openId));
    }

    //用户认证
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //先查出来userInfo
        UserInfo userInfo = getUserInfoById(userId);
        if (userInfo!=null){
            //将认证信息填充到用户信息中
            userInfo.setName(userAuthVo.getName());
            userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
            userInfo.setCertificatesType(userAuthVo.getCertificatesType());
            userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
            userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
            //更新用户信息
            this.updateById(userInfo);
        }
    }

    //根据用户id查询用户
    @Override
    public UserInfo getUserInfoById(Long userId) {
        UserInfo userInfo = baseMapper.selectById(userId);
        if (userInfo!=null){
            return userInfo;
        }
        return null;
    }

    //用户分页查询
    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        //获取查询条件值
        String name = userInfoQueryVo.getKeyword(); //姓名
        Integer authStatus = userInfoQueryVo.getAuthStatus();//用户认证状态
        Integer status = userInfoQueryVo.getStatus();//用户状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();//开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();//结束时间
        //封装条件
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)){
            //对姓名进行模糊查询
            queryWrapper.like("name",name);
        }
        if (!StringUtils.isEmpty(authStatus)){
            //对认证状态进行查询
            queryWrapper.eq("auth_status",authStatus);
        }
        if (!StringUtils.isEmpty(status)){
            //对用户状态进行查询
            queryWrapper.eq("status",status);
        }
        if (!StringUtils.isEmpty(createTimeBegin)){
            //大于开始时间
            queryWrapper.le("create_time",createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)){
            //大于开始时间
            queryWrapper.ge("create_time",createTimeEnd);
        }
        //进行分页查询
        Page<UserInfo> pages = this.baseMapper.selectPage(pageParam, queryWrapper);
        //对查询结果进行封装
        pages.getRecords().stream().forEach(item->{
            this.fullUserInfo(item);
        });
        //返回查询结果
        return pages;
    }

    //用户锁定
    @Override
    public void lock(Long id, Integer status) {
        //先查询用户
        UserInfo userInfo = baseMapper.selectById(id);
        if (userInfo!=null){
            if (status==0||status==1){
                userInfo.setStatus(status);
                baseMapper.updateById(userInfo);
            }
        }
    }

    //显示用户详情
    @Override
    public Map<String, Object> showDetail(Long userId) {
        Map<String,Object> map=new HashMap<>();
        //查询并封装用户
        UserInfo userInfo = baseMapper.selectById(userId);
        fullUserInfo(userInfo);
        map.put("userInfo",userInfo);
        //查询并封装就诊人信息
        List<Patient> patientList = patientService.getPatientList(userId);
        map.put("patientList",patientList);
        return map;
    }

    //用户审批
    @Override
    public void approval(Long userId, Integer authStatus) {
        //-1为未通过，2为通过。给用户设置状态
        if (authStatus==2||authStatus==-1){
            UserInfo userInfo = baseMapper.selectById(userId);
            if (userInfo!=null){
                userInfo.setAuthStatus(authStatus);
                //更新
                baseMapper.updateById(userInfo);
                System.out.println(userInfo);
            }
        }
    }

    //填充用户信息
    private void fullUserInfo(UserInfo userInfo) {
        //封装用户认证编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //封装用户状态
        String statusString=userInfo.getStatus().intValue()==0?"锁定":"正常";
        userInfo.getParam().put("statusString",statusString);
    }
}
